package xyz.zchao.blog.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import xyz.zchao.blog.annotation.IgnoreToken;
import xyz.zchao.blog.pojo.Role;
import xyz.zchao.blog.service.RoleService;
import xyz.zchao.blog.util.PageResultVO;
import xyz.zchao.blog.util.ResultCode;
import xyz.zchao.blog.util.ResultVO;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleService roleService;


    @IgnoreToken
    @GetMapping("/list")
    public PageResultVO getRoles(@RequestParam(required = false) Integer page, @RequestParam(required = false) Integer limit) {
        List<Role> roles = roleService.retrieveAllByPaging(page, limit);
        long count = roleService.getCount();
        return new PageResultVO(ResultCode.SUCCESS, roles, count);
    }

    @IgnoreToken
    @GetMapping("/list/{rid}")
    public ResultVO getRole(@PathVariable("rid") Integer rid) {
        Role tag = roleService.retrieveById(rid);
        return new ResultVO(ResultCode.SUCCESS, tag);
    }

    @PutMapping("/list/{rid}")
    public ResultVO updateRole(@PathVariable("rid") Integer rid, @RequestBody @Valid Role record) {
        record.setRoleId(rid);
        roleService.update(record);
        return new ResultVO(ResultCode.SUCCESS, null);
    }

    @DeleteMapping("/list/{rid}")
    public ResultVO deleteRole(@PathVariable("rid") Integer rid) {
        roleService.deleteById(rid);
        return new ResultVO(ResultCode.SUCCESS, null);
    }

    @PostMapping("/add")
    public ResultVO addRoles(@RequestBody @Valid Role record) {
        roleService.create(record);
        return new ResultVO(ResultCode.SUCCESS, null);
    }

}
